package site.ruyi.devclient.client.dubbo.impl;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javafx.scene.control.TextField;
import site.ruyi.devclient.client.dubbo.IDubboClient;
import site.ruyi.devclient.core.AlertUtil;
import site.ruyi.devclient.core.FormDialog;
import site.ruyi.devclient.core.UserData;
import site.ruyi.devclient.util.InteractSocket;

/**
 * 单台Dubbo连接客户端
 * @author self
 *
 */
public class DubboClientImpl implements IDubboClient {

	private static final Logger log = LoggerFactory.getLogger(DubboClientImpl.class);

	//执行线程池
    private static final ExecutorService taskPool = Executors.newCachedThreadPool();

	//客户端名称
	private static final String CLIENT_NAME = "Dubbo客户端(单机)";

	//交互式Socket
	private InteractSocket socket;

	//连接信息
	private ConnectInfo connectInfo;

	public DubboClientImpl(){
		UserData.getDB().exec("CREATE TABLE IF NOT EXISTS dubbo_client(id TEXT NOT NULL ON CONFLICT FAIL UNIQUE ON CONFLICT REPLACE,host TEXT,port TEXT,create_time TIMESTAMP default (datetime('now', 'localtime')))");
	}

	@Override
	public String getName() {
		return CLIENT_NAME;
	}

	@Override
	public ConnectInfo getConnectInfo() {
		return connectInfo;
	}

	@Override
	public boolean init() {
		log.info("初始化客户端组件！");
		return createConnection();
	}

	/**
	 * 创建连接
	 * @return
	 */
	private boolean createConnection() {
		log.info("创建Socket连接！");
		TextField hostTextField = new TextField("127.0.0.1");
		TextField portTextField = new TextField("20880");

		Map<String,Object> lastConnInfo=UserData.getDB().find("select host,port from dubbo_client order by create_time desc limit 1");
		if(lastConnInfo!=null&&!lastConnInfo.isEmpty()){
			hostTextField.setText(String.valueOf(lastConnInfo.get("host")));
			portTextField.setText(String.valueOf(lastConnInfo.get("port")));
		}

		FormDialog newConnForm = new FormDialog("新建链接"
				,new FormDialog.Item("主机：", hostTextField)
				,new FormDialog.Item("端口：", portTextField));
		Optional<Boolean> result = newConnForm.showAndWait();
		if(result.isPresent()) {
			String host = hostTextField.getText();
			int port = Integer.valueOf(portTextField.getText());
			log.info("Socket连接参数 -> host:"+host+",port:"+port);
			this.connectInfo = new ConnectInfo(host, port);
			try {
				socket = new InteractSocket(host, port);
				log.info("已连接到Dubbo服务器。");

				String connId=DigestUtils.md5Hex(host+"_"+port);
				UserData.getDB().save("insert into dubbo_client(id,host,port) values(?,?,?)", connId,host,port);

				return true;
			} catch (IOException e) {
				AlertUtil.exception("连接失败", e);
			}
		}
		return false;
	}

	@Override
	public String exeCmd(String cmd) {
		if(cmd==null||"".equals(cmd.trim())) {
			return null;
		}
		try {
			log.info("执行命令："+cmd);
			//命令如果没有换行符则补充一个
			if(!cmd.endsWith("\n")) {
				cmd+="\n";
			}

			String result=socket.sendCommand(cmd);
			log.info("执行结果："+result);
			return result;
		} catch (IOException e) {
			AlertUtil.exception(e);
		}
		return null;
	}

	@Override
	public void close() throws IOException {
		if(socket!=null) {
			socket.close();
		}
	}
}
